﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using SoufunData.DB;

namespace SoufunData
{
    public partial class ExToDbZProjectContract : DevExpress.XtraEditors.XtraForm
    {
        public ExToDbZProjectContract()
        {
            InitializeComponent();
        }

        private void btn_excelPath_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {

            openFileDialog1.Filter = "Excel文件|*.xls;*.xlsx";
            openFileDialog1.FileName = "";
            openFileDialog1.ShowDialog();
            string fileName = openFileDialog1.FileName;
            btn_excelPath.Text = fileName;

            gridControl2.DataSource = null;
            gridView2.Columns.Clear();
            gridView2.GroupPanelText = "请选择Excel文件";
            if (fileName == "")
            {
                return;
            }
            DataSet ds = Common.LoadDataFromExcel(fileName);
            if (ds == null || ds.Tables.Count == 0)
            {
                string strError = "读取Excel时发生错误，请核对：\r\n ";
                strError += "1，导入时请在Excel中关闭想要导入的文件！\r\n";
                strError += "2，导入的Excel表中的工作表名称必须为Sheet1,否者程序无法读取！\r\n";
                strError += "3，请确保您的计算机安装了Microsoft Office！\r\n";
                strError += "4，请确保导入的Excel文件正常！";
                XtraMessageBox.Show(strError);
                btn_excelPath.Text = "";
                return;
            }
            if (!CheckExcelColumnsName(ds.Tables[0]))
            {
                btn_excelPath.Text = "";
                return;
            }
            gridControl2.DataSource = ds.Tables[0];
            gridView2.GroupPanelText = "共有" + ds.Tables[0].Rows.Count + "条数据";
        }


        private void AddData()
        {
           
            DataTable dtOld = (DataTable)gridControl2.DataSource;

            DataTable dt = dtOld.Copy();
            dt.Rows.Clear();
            foreach (DataRow dataRow in dtOld.Rows)
            { 
                dt.Rows.Add(dataRow.ItemArray);
            }
             
            int insertRowsCount = 500;//一次性插入数据库行数
            int succeedrows = 0;//成功插入数据行数
            StringBuilder strSql = new StringBuilder();

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                DataRow row = dt.Rows[i];
                string strProjectName = row["项目名称"].ToString();
                string strXzq = row["行政区"].ToString();
                string strBoard = row["版块"].ToString();
                string strFloorCount = row["建筑形态"].ToString();
                string strSellTime = row["销售时间"].ToString();
                string strSellCount = row["销售套数（套）"].ToString();
                string strSellArea = row["销售面积（㎡）"].ToString();
                string strSellMoney = row["销售金额（万元）"].ToString();
                string strSellFold = row["销售均价（元/㎡）"].ToString();
                string strHouseType = row["户型"].ToString();
                string strAreaScope = row["销售面积段(㎡）"].ToString();
                string strUnitPrice = row["销售单价段（元/㎡）"].ToString();
                string strTotalPrice = row["销售总价段（万元）"].ToString();
                string strPropertyType = row["物业类型"].ToString();
                string strIsBaoZhangFang = row["是否保障房"].ToString();
                string strCompany = row["开发企业"].ToString();
                string strGroup = row["所属集团"].ToString();
                if (i % insertRowsCount == 0)
                {
                    strSql = new StringBuilder();
                    strSql.Append("Insert into tzprojectcontract (");
                    strSql.Append("ProjectName,");
                    strSql.Append("AdministratiVeregion,");
                    strSql.Append("Board,");
                    strSql.Append("FloorCount,");
                    strSql.Append("SellTime,");
                    strSql.Append("SellCount,");
                    strSql.Append("SellArea,");
                    strSql.Append("SellMoney,");
                    strSql.Append("SellFold,");
                    strSql.Append("HouseType,");
                    strSql.Append("AreaScope,");
                    strSql.Append("UnitPrice,");
                    strSql.Append("TotalPrice,");
                    strSql.Append("PropertyType,");
                    strSql.Append("IsBaoZhangFang,");
                    strSql.Append("Company,");
                    strSql.Append("`Group`");  
                    strSql.Append(") value  ");
                }
                strSql.Append("('");
                strSql.Append(strProjectName);
                strSql.Append("','");
                strSql.Append(strXzq);
                strSql.Append("','");
                strSql.Append(strBoard);
                strSql.Append("','");
                strSql.Append(strFloorCount);
                strSql.Append("','");
                strSql.Append(strSellTime);
                strSql.Append("',");
                strSql.Append(strSellCount);
                strSql.Append(",");
                strSql.Append(strSellArea);
                strSql.Append(",");
                strSql.Append(strSellMoney);
                strSql.Append(",");
                strSql.Append(strSellFold);
                strSql.Append(",'");
                strSql.Append(strHouseType);
                strSql.Append("','");
                strSql.Append(strAreaScope);
                strSql.Append("','");
                strSql.Append(strUnitPrice);
                strSql.Append("','");
                strSql.Append(strTotalPrice);
                strSql.Append("','");
                strSql.Append(strPropertyType);
                strSql.Append("','");
                strSql.Append(strIsBaoZhangFang);
                strSql.Append("','");
                strSql.Append(strCompany);
                strSql.Append("','");
                strSql.Append(strGroup);                 
                strSql.Append("'),");

                if ((i + 1) % insertRowsCount == 0
                    || i == dt.Rows.Count - 1)
                {
                    strSql.Remove(strSql.Length - 1, 1);
                    succeedrows += DbHelper.ExecuteSql(strSql.ToString());
                }
            }

            if (dt.Rows.Count == succeedrows)
            {
                XtraMessageBox.Show("添加成功！");
                BeginInvoke(new MethodInvoker(() =>
                {
                    btn_excelPath.Text = "";
                    gridControl2.DataSource = null;
                }));
            }
            else
            {
                int failedCount = dt.Rows.Count - succeedrows;
                XtraMessageBox.Show("共记" + dt.Rows.Count + "条数据，其中"
                    + failedCount + "条数据添加失败！");
            }
            BeginInvoke(new MethodInvoker(() =>
            {
               
                btn_excelPath.Enabled = true;
                btn_add.Enabled = true;
            }));
        }

        private void btn_add_Click(object sender, EventArgs e)
        {
            if (btn_excelPath.Text.Trim()=="")
            {
                XtraMessageBox.Show("请先选择Excel！");
                return;
            }
            if (!CheckDataValid())
            {
                return;
            }
             
            btn_excelPath.Enabled = false;
            btn_add.Enabled = false;
            Thread t = new Thread(AddData) { IsBackground = true };
            t.Start();
        }

        #region 数据完整性检测
        private bool CheckDataValid()
        {
            DataTable dt = (DataTable)gridControl2.DataSource;
            StringBuilder strErrors = new StringBuilder();

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                DataRow dr = dt.Rows[i];
                string strProName = dr["项目名称"].ToString();
                string strXzq = dr["行政区"].ToString();
                string strBoard = dr["版块"].ToString();
                string strSellTime = dr["销售时间"].ToString();
                string strSellCount = dr["销售套数（套）"].ToString();
                string strSellArea = dr["销售面积（㎡）"].ToString();
                string strSellMoney = dr["销售金额（万元）"].ToString();
                string strSellFold = dr["销售均价（元/㎡）"].ToString();
                if (strProName.Trim() == "")
                {
                    strErrors.Append("第" + (i + 2) + "行数据中的【项目名称】为空！\r\n");
                }
                if (strXzq.Trim() == "")
                {
                    strErrors.Append("第" + (i + 2) + "行数据中【行政区】未填！\r\n");
                }
                if (strBoard.Trim() == "")
                {
                    strErrors.Append("第" + (i + 2) + "行数据中【板块】未填！\r\n");
                }
                DateTime tempTime = new DateTime();
                if (!DateTime.TryParse(strSellTime, out tempTime))
                {
                    strErrors.Append("第" + (i + 2)
                   + "行数据中【销售时间】的数据格式有误，应为时间格式【yyyy年MM月dd日】！\r\n");
                }
                int intSellcount = 0;
                if (! int.TryParse(strSellCount,out intSellcount))
                {
                    strErrors.Append("第" + (i + 2) + "行数据中【销售套数（套）】不为整数！\r\n");
                }
                float floatTemp = 0;
                if (!float.TryParse(strSellArea, out floatTemp))
                {
                    strErrors.Append("第" + (i + 2) + "行数据中【销售面积（㎡）】不为正确的数字格式！\r\n");
                }
                if (!float.TryParse(strSellMoney, out floatTemp))
                {
                    strErrors.Append("第" + (i + 2) + "行数据中【销售金额（万元）】不为正确的数字格式！\r\n");
                }
                if (!float.TryParse(strSellFold, out floatTemp))
                {
                    strErrors.Append("第" + (i + 2) + "行数据中【销售均价（元/㎡）】不为正确的数字格式！\r\n");
                }
            }
            if (strErrors.ToString() != "")
            {
                XtraMessageBox.Show("您选择的Excel中的数据存在以下错误：\r\n" +
                    strErrors);
                return false;
            }
            return true;
        }

        private bool CheckExcelColumnsName(DataTable dt)
        {
            StringBuilder strErrors = new StringBuilder();
            if (!dt.Columns.Contains("项目名称"))
            {
                strErrors.Append("【项目名称】、");
            }
            if (!dt.Columns.Contains("行政区"))
            {
                strErrors.Append("【行政区】、");
            }
            if (!dt.Columns.Contains("版块"))
            {
                strErrors.Append("【版块】、");
            }
            if (!dt.Columns.Contains("建筑形态"))
            {
                strErrors.Append("【建筑形态】、");
            }
            if (!dt.Columns.Contains("销售时间"))
            {
                strErrors.Append("【销售时间】、");
            }
            if (!dt.Columns.Contains("销售套数（套）"))
            {
                strErrors.Append("【销售套数（套）】、");
            }
            if (!dt.Columns.Contains("销售面积（㎡）"))
            {
                strErrors.Append("【销售面积（㎡）】、");
            }
            if (!dt.Columns.Contains("销售金额（万元）"))
            {
                strErrors.Append("【销售金额（万元）】、");
            }
            if (!dt.Columns.Contains("销售均价（元/㎡）"))
            {
                strErrors.Append("【销售均价（元/㎡）】、");
            }
            if (!dt.Columns.Contains("户型"))
            {
                strErrors.Append("【户型】、");
            }
            if (!dt.Columns.Contains("销售面积段(㎡）"))
            {
                strErrors.Append("【销售面积段(㎡）】");
            }
            if (!dt.Columns.Contains("销售单价段（元/㎡）"))
            {
                strErrors.Append("【销售单价段（元/㎡）】");
            }
            if (!dt.Columns.Contains("销售总价段（万元）"))
            {
                strErrors.Append("【销售总价段（万元）】");
            }
            if (!dt.Columns.Contains("物业类型"))
            {
                strErrors.Append("【物业类型】");
            }
            if (!dt.Columns.Contains("是否保障房"))
            {
                strErrors.Append("【是否保障房】");
            }
            if (!dt.Columns.Contains("开发企业"))
            {
                strErrors.Append("【开发企业】");
            }
            if (!dt.Columns.Contains("所属集团"))
            {
                strErrors.Append("【所属集团】");
            }
          
            if (strErrors.ToString() != "")
            {
                XtraMessageBox.Show("您选择的广告投放Excel表数据不正常,缺少以下数据列:\r\n" +
                                    strErrors);
                return false;
            }
            return true;
        }
        #endregion
         
    }
}